#include "tcpserver.hpp"
#include "Json.hpp"
#include "Caculate.hpp"

using namespace std;
using namespace Protocal;

using call_t = function<Response(Request&)>;

class Service
{

private:
    call_t _func;

public:
    Service(){}

    Service(call_t func):_func(func)
    {}

    void ServiceHelper(sock_addr sock, Analyze peer)
    {
        int fd = sock->getfd();
        string clientinfo = "[" + peer.getip() + ":" + to_string(peer.getport()) + "]";

        string buffer;
        while (true)
        {
            sleep(1);
            int n = sock->Recv(buffer);
            if (n <= 0)
            {
                Log(Info, "quit or dataNull");
                break;
            }

            // 判定读取的数据是否完整Decode
            string ret = Decode(buffer);
            if (ret.empty())
                continue;

            // 到这里数据一定是完整的

            // 接下来就要将数据反序列化
            Request req;
            req.DeSerislize(ret);

            Response resp = _func(req); //处理逻辑

            //将数据再序列化
            string ret_str = resp.Serislize();
            //将序列化的数据添加报头
            Encode(ret_str);

            //发送数据
            sock->Send(ret_str);
            cout << "send data: " << ret_str << endl;
        }

        // ::close(fd);
    }
};

int main()
{

    Calculate cal;
    Service service(bind(&Calculate::Excute, &cal, placeholders::_1));
    io_server_t func2 = bind(&Service::ServiceHelper, &service, placeholders::_1, placeholders::_2);
    unique_ptr<TcpServer> ptr = make_unique<TcpServer>(2020, func2);

    ptr->Start();

    return 0;
}